﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using PersonaLibrary.Data;
using PersonaLibrary.Properties;

namespace PersonaLibrary.DbUpdater
{
	internal sealed class DbVersionController
	{
		private static readonly DbVersionController _instanse = new DbVersionController();

		private Dictionary<Version, IVersion> _versions = new Dictionary<Version, IVersion>();

		private DbVersionController()
		{
			using (DbConnection connection = new SqlConnection(Settings.Default.PersonalizationConnectionString))
			{
				connection.Open();

				string commandText =
					"IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Version')"
					+ "CREATE TABLE Version(Id int NOT NULL identity, Version nvarchar(500), Updated date)";

				using (DbCommand command = new SqlCommand(commandText))
				{
					command.Connection = connection;
					command.ExecuteNonQuery();
				}
			}

			IVersion version1 = new Version1();
			_versions.Add(version1.Version, version1);
		}

		public static DbVersionController Instanse
		{
			get { return _instanse; }
		}

		public void UpdateIfNeeded()
		{
			string str_select = "SELECT * FROM dbo.Version";

			DataSet ds = new DataSet();
			using (SqlDataAdapter da = new SqlDataAdapter(str_select, Settings.Default.PersonalizationConnectionString))
			{
				da.Fill(ds);
			}

			if (ds.Tables[0].Rows.Count == 0)
			{
				using (DbConnection connection = new SqlConnection(Settings.Default.PersonalizationConnectionString))
				{
					connection.Open();

					string defaultVersionCommand =
						string.Format("INSERT INTO dbo.Version (Version, Updated) VALUES ('1.0.0.0', '{0}')",
						              DateTime.Now.ToShortDateString());

					using (DbCommand command = new SqlCommand(defaultVersionCommand))
					{
						command.Connection = connection;
						command.ExecuteNonQuery();
					}
				}
			}
		}
	}
}
